<template>
	<div ref="useTable"></div>
</template>

<script>
	export default {
		props: {
			tableRefs: {
				type: Object,
				default: null
			},
			navHeight: {
				type: Number,
				default: 0
			},
			bottom: {
				type: Number,
				default: 16
			},
			right: {
				type: Number,
				default: 16
			},
			top: {
				type: Number,
				default: 0
			}
		},
		data() {
			return {
				height: 0,
				tblHeight: 0,
				body: null,
				containers: [],
				tableObj: null,
				tableHeadHeight: 0,
				tablePaginationHeight: 0
			};
		},
		mounted() {
			this.body = document.getElementsByTagName('uni-page-body')[0];
			this.height = this.body.clientHeight;

			this.containers = this.$refs.useTable.parentElement.querySelectorAll('.container');

			this.tableStyle();
			this.tableChange();

			window.onresize = () => {
				if (this.tableRefs) {
					this.tableRefs.doLayout();
				}
				this.tableChange();
			};
		},
		methods: {
			tableStyle() {
				if (this.tableObj && this.tableObj.ele) {
					return;
				}
				this.containers.forEach(ele => {
					// 16 间距
					if (![...ele.classList].includes('use-table')) {
						this.height -= ele.clientHeight - 16;
					} else {
						this.tableObj = {
							offset: this.$api.offset(ele),
							ele
						};
					}
				});

				if (this.tableObj.ele.childNodes.length) {
					this.tableObj.ele.childNodes.forEach(ele => {
						if ([...ele.classList].includes('table-head')) {
							let getComputedStyle = window.getComputedStyle(ele);
							this.tableHeadHeight = ele.offsetHeight + parseInt(getComputedStyle.marginBottom);
						} else if ([...ele.classList].includes('el-pagination')) {
							this.tablePaginationHeight = ele.offsetHeight;
						}
					});
				}
			},
			tableInit(height) {
				this.tableObj.ele.style.position = 'initial';
				this.tableObj.ele.style.height = this.tableObj.ele.clientHeight + height + 'px';
			},
			tableChange() {
				this.tableObj.offset = this.$api.offset(this.tableObj.ele);
				this.tableObj.ele.style.position = 'fixed';
				this.tableObj.ele.style.top = this.tableObj.offset.t + 'px';
				this.tableObj.ele.style.left = this.tableObj.offset.l + 'px';
				this.tableObj.ele.style.bottom = this.bottom + 'px';
				this.tableObj.ele.style.right = this.right + 'px';
				// 40 为上下 padding 20
				this.tblHeight = (parseInt(this.tableObj.ele.style.height) || this.tableObj.ele.clientHeight) - 40 - this
					.tableHeadHeight - this.tablePaginationHeight;
				this.tableObj.ele.querySelector('.el-table').style.height = this.tblHeight + 'px';
			}
		},
		created() {
			uni.$on('fold', res => {
				if (res) {
					this.tableObj.ele.style.left = 'calc(16px + var(--window-left))';
				} else {
					this.tableObj.ele.style.left = 'calc(16px + var(--window-left))';
				}
			});
		}
	};
</script>

<style></style>
